package org.ourgrid.broker.business.schedulerdata.executor;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.business.dao.BrokerDAOFactory;
import org.ourgrid.broker.business.dao.JobDAO;
import org.ourgrid.broker.business.schedulerdata.SchedulerData;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.response.OperationSucceedResponseTO;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AddJobExecutor extends AbstractSchedulerDataExecutor {
	
	/**
	 * <ADD_JOB jobID='int' errorMessage='String'/> 
	 */
	public List<IResponseTO> execute(SchedulerData command) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		Document logDocFile = super.getXMl(command.getXml());
		
		Element element = logDocFile.getDocumentElement();
		
		Integer jobID = Integer.valueOf(element.getAttribute("jobID"));
		String errorMessage = element.getAttribute("errorMessage");
		JobDAO jobDAO = BrokerDAOFactory.getInstance().getJobDAO();
		
		String clientAddress = jobDAO.getBrokerControlClientAddress();
		
		jobDAO.addJob(jobID);
		
		OperationSucceedResponseTO to = new OperationSucceedResponseTO();
		to.setClientAddress(clientAddress);
		
		if (errorMessage != null && !errorMessage.equals("")) {
			to.setErrorCause(new Exception(errorMessage));
		} else if (jobID != null) {
			to.setResult(jobID);
		}
		
		responses.add(to);
		
		return responses;
	}
}
